package com.hjj.springboot.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hjj.springboot.config.LogType;
import com.hjj.springboot.config.SystemLogs;
import com.hjj.springboot.entity.ProductSwiperImage;
import com.hjj.springboot.entity.R;
import com.hjj.springboot.service.IProductSwiperImageService;
import com.hjj.springboot.util.DateUtil;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/productSwiperImage")
public class AdminProductSwiperImageController {

    @Autowired
    private IProductSwiperImageService productSwiperImageService;

    @Value("${productSwiperImagesFilePath}")
    private String productSwiperImagesFilePath;

    @GetMapping("/list/{id}")
    public R list(@PathVariable(value = "id") Integer id) {
        List<ProductSwiperImage> list = productSwiperImageService.list(new QueryWrapper<ProductSwiperImage>().eq("productId",id));
        HashMap<String, Object> map = new HashMap<>();
        map.put("list", list);
        return R.ok(map);
    }

    @SystemLogs(operation = "商品轮播图片",type = LogType.ADD)
    @RequestMapping("/add")
    public R add(@RequestBody ProductSwiperImage productSwiperImage) {
        productSwiperImageService.saveOrUpdate(productSwiperImage);
        return R.ok();
    }

    @SystemLogs(operation = "商品轮播图片",type = LogType.DELETE)
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id") Integer id) {
        productSwiperImageService.removeById(id);
        return R.ok();
    }

    //    上传商品图片
    @SystemLogs(operation = "商品轮播图片",type = LogType.UPLODE)
    @RequestMapping("/uploadImage")
    public Map<String,Object> uploadImage(MultipartFile file) throws Exception {
        Map<String,Object> reultMap=new HashMap<>();
        if(!file.isEmpty()){
            String originalFilename= file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFileName= DateUtil.getCurrentDateStr()+suffix;
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(productSwiperImagesFilePath+newFileName));
            reultMap.put("code",0);
            reultMap.put("msg","上传成功");
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("title",newFileName);
            dataMap.put("src","img/productSwiperImgs/"+newFileName);
            reultMap.put("data",dataMap);
        }
        return reultMap;
    }
}
